package com.zone.domain.strategy.service.rule.tree.impl;

import com.zone.domain.strategy.model.valobj.AwardStockSubTaskVO;
import com.zone.domain.strategy.model.valobj.RuleActionEnum;
import com.zone.domain.strategy.service.IRaffleStock;
import com.zone.domain.strategy.service.rule.tree.ILogicTreeNode;
import com.zone.domain.strategy.service.rule.tree.factory.DefaultTreeNodeFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author: zongzi
 * @description: 库存处理
 * @date: 2024/6/11
 */
@Slf4j
@Component("rule_stock")
public class RuleStockTreeNode implements ILogicTreeNode {
    @Autowired
    private IRaffleStock raffleStock;

    @Override
    public DefaultTreeNodeFactory.TreeNodeActionEntity logic(Long strategyId, String userId, Integer awardId, String ruleValue) {
        // 扣减奖品库存
        boolean descAwardStockResult = raffleStock.descAwardStock(strategyId, awardId);
        if (descAwardStockResult) {
            // 扣减奖品库存成功，将任务加入到阻塞队列中
            AwardStockSubTaskVO stockSubTaskVO = AwardStockSubTaskVO.builder().strategyId(strategyId).awardId(awardId).build();
            raffleStock.offerAwardStockSubTask(stockSubTaskVO);

            return DefaultTreeNodeFactory.TreeNodeActionEntity.builder()
                    .strategyAward(DefaultTreeNodeFactory.StrategyAwardVO.builder()
                            .awardId(awardId)
                            .build())
                    .ruleAction(RuleActionEnum.INTERCEPT)
                    .build();
        }
        // 库存扣减失败放行请求
        return DefaultTreeNodeFactory.TreeNodeActionEntity.builder()
                .ruleAction(RuleActionEnum.ALLOW)
                .strategyAward(DefaultTreeNodeFactory.StrategyAwardVO.builder()
                        .awardId(awardId)
                        .build())
                .build();
    }
}
